package com.adlx.dingdong.mall.service.impl;


import com.adlx.dingdong.mall.domain.User;
import com.adlx.dingdong.mall.domain.UserCriteria;
import com.adlx.dingdong.mall.mapper.UserMapper;
import com.adlx.dingdong.mall.user.api.UserFeignClient;
import com.adlx.dingdong.mall.user.dto.UserDTO;
import com.adlx.dingdong.mall.user.dto.UserRegDTO;
import com.adlx.dingdong.mall.user.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static com.adlx.dingdong.mall.commons.utils.Beans.transfrom;

@Slf4j
@RefreshScope
@RestController
public class UserFeignClientImpl implements UserFeignClient {

    @Autowired
    private UserMapper userMapper;

//    @Autowired
//    private OrderService orderService;

    @Override
    public UserDTO getUserByUsername(@PathVariable("username") String username) {
        UserCriteria userCriteria = new UserCriteria();
        userCriteria.createCriteria().andAccountEqualTo(username);
        List<User> userList = userMapper.selectByExample(userCriteria);
        User user = userList.isEmpty() ? null : userList.get(0);
        UserDTO userDTO = transfrom(UserDTO.class, user);
        userDTO.setId(Long.valueOf(user.getId()));
        userDTO.setUsername(user.getAccount());
        userDTO.setPassword(user.getPwd());
        return userDTO;
    }

    @Override
    public UserDTO getByUsernameAndPasswordDTO(UserRegDTO userRegDTO) {
        UserCriteria userCriteria = new UserCriteria();
        userCriteria.createCriteria().andAccountEqualTo(userRegDTO.getUsername()).andPwdEqualTo(userRegDTO.getPassword());
        List<User> userList = userMapper.selectByExample(userCriteria);
        return userList.isEmpty() ? null : transfrom(UserDTO.class, userList.get(0));
    }

    @Override
    @Transactional
    public UserVO get(@PathVariable("uid") Long uid) {
        User user = userMapper.selectByPrimaryKey(uid.intValue());
        UserVO userVO = transfrom(UserVO.class, user);
//        orderService.placeOrder(30,"111");
        return userVO;
    }


}
